package com.villaday.idf.activity;

import android.content.Intent;
import android.graphics.Bitmap;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.custom.EnvelopeConfirmDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.SettingEnvelopePerentDialog;
import com.villaday.idf.model.fission;
import com.villaday.idf.model.fissionEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.bumptech.glide.load.DecodeFormat.PREFER_ARGB_8888;

/*
 * 设置裂变红包
 * */
public class FissionRedEnvelopeActivity extends BaseActivity implements OkHttpUtil.OnDataListener, BaseDialog.OnItemClickListener, SettingEnvelopePerentDialog.OnSetEnvelopListener {


    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.togglebutton)
    public ToggleButton tb1;
    @BindView(R.id.ll_red_envelope_rabit)
    public LinearLayout llRedEnvelopeRabit;
    @BindView(R.id.tv_percent)
    public TextView tvPercent;
    @BindView(R.id.sdv)
    public SimpleDraweeView sdv;
    @BindView(R.id.sdv_bg)
    ImageView sdvBg;


    private LoadingDialog loadingDialog;
    private boolean isAllowFission;
    private String fissionPercent;
    private String fissionImageUrl;

    private String Percent;
    private Gson gson = new GsonBuilder().create();

    @Override
    protected int getViewResId() {
        return R.layout.activity_fission_red_envelope;
    }

    @Override
    protected void init() {
        ToolBarUtil.initToolBar(toolbarText, "设置裂变红包", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        setToggleButton();

        Intent intent = getIntent();
        isAllowFission = intent.getBooleanExtra("allowFission", false);
        fissionPercent = intent.getStringExtra("fissionPercent");
        fissionImageUrl = intent.getStringExtra("fissionImageUrl");
//        sdv.setImageURI(PhoneUtil.getHead(fissionImageUrl));
        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.ic_replace)
                .error(R.drawable.ic_replace)
                .priority(Priority.HIGH)
                .format(PREFER_ARGB_8888)
                .centerCrop();
        Glide.with(this)
                .asBitmap()//强制Glide返回一个Bitmap对象
                .load(fissionImageUrl)
                .apply(options)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {

                        int width = resource.getWidth();
                        int height = resource.getHeight();
//                        sdvBg.getLayoutParams().width = PhoneUtil.getPhoneWidth(FissionRedEnvelopeActivity.this);
//                        sdvBg.getLayoutParams().height = PhoneUtil.getPhoneWidth(FissionRedEnvelopeActivity.this) * height / width;
//                        sdvBg.setLayoutParams();
//                        sdvBg.requestLayout();
//                        sdvBg.setImageBitmap(resource);
                        ViewGroup.LayoutParams layoutParams = sdvBg.getLayoutParams();
                        layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
                        layoutParams.height = PhoneUtil.getPhoneWidth(FissionRedEnvelopeActivity.this) * height / width;
                        sdvBg.setLayoutParams(layoutParams);
                        sdvBg.setBackgroundColor(getResources().getColor(R.color.transparent));
                        sdvBg.setImageBitmap(resource);
                    }


                });

        tb1.setChecked(isAllowFission);
        if (isAllowFission) {
            tvPercent.setText(fissionPercent + "%");
            llRedEnvelopeRabit.setVisibility(View.VISIBLE);
        } else {
            llRedEnvelopeRabit.setVisibility(View.GONE);
            tvPercent.setText("");
        }

    }

    @OnClick({R.id.btn, R.id.ll_red_envelope_rabit})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.btn: {
                if (isAllowFission) {
                    EnvelopeConfirmDialog confirmDialog = EnvelopeConfirmDialog.newInstance("确定关闭？", "关闭后团队好友的收入会减少,影响团队积极性", "取消", "确定");
                    confirmDialog.setOnItemClickListener(FissionRedEnvelopeActivity.this);
                    confirmDialog.show(getFragmentManager());
                } else {
                    String percent = "";
                    if (!TextUtils.isEmpty(tvPercent.getText().toString())) {
                        percent = tvPercent.getText().toString().substring(0, tvPercent.getText().toString().length() - 1);
                    }
                    SettingEnvelopePerentDialog envelopePerentDialog = SettingEnvelopePerentDialog.newInstance(FissionRedEnvelopeActivity.this, 0, percent);
                    envelopePerentDialog.setListener(FissionRedEnvelopeActivity.this);
                    envelopePerentDialog.show(getFragmentManager());
                }
            }
            break;

            case R.id.ll_red_envelope_rabit: {
                String percent = "";
                if (!TextUtils.isEmpty(tvPercent.getText().toString())) {
                    percent = tvPercent.getText().toString().substring(0, tvPercent.getText().toString().length() - 1);
                }
                SettingEnvelopePerentDialog envelopePerentDialog = SettingEnvelopePerentDialog.newInstance(FissionRedEnvelopeActivity.this, 1, percent);
                envelopePerentDialog.setListener(FissionRedEnvelopeActivity.this);
                envelopePerentDialog.show(getFragmentManager());
            }
            break;
        }
    }

    private void setToggleButton() {
        tb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {


                } else {

                }
            }
        });
    }


    private void modifyRabit(boolean allowFission, String fissionPercent) {
        loadingDialog = LoadingDialog.newInstance("请求中...");
        loadingDialog.show(getFragmentManager());
        Map<String, Object> map = new HashMap<>();
        if (allowFission) {
            OkHttpUtil.postJson(this, Constant.URL.save_fission, new fission(allowFission, fissionPercent), map, this);
        } else {
            OkHttpUtil.postJson(this, Constant.URL.save_fission, new fission(allowFission), map, this);
        }
    }


    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            LogeUtil.e("save_fission", json);
            dismissLoading();
            fissionEntity fe = gson.fromJson(json, fissionEntity.class);
            if (Constant.Strings.SUC.equals(fe.getCode())) {
                isAllowFission = !isAllowFission;
                tb1.performClick();
                llRedEnvelopeRabit.setVisibility(llRedEnvelopeRabit.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                if (!TextUtils.isEmpty(Percent))
                    tvPercent.setText(Percent + "%");
            } else {
                ToastUtil.initToast(FissionRedEnvelopeActivity.this, fe.getMsg());
            }
        }

    }

    @Override
    public void onFailure(String url, String error) {

    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirmDialog: {
//                isAllowFission = !isAllowFission;
//                tb1.performClick();
                modifyRabit(false, "50");
            }
            break;
        }
    }

    @Override
    public void crateEnvelope(String groupRabit, int type) {
//        isAllowFission = !isAllowFission;
//        tb1.performClick();
        Percent = groupRabit;
        if (type == 0) {
            modifyRabit(true, groupRabit);
        } else {
            loadingDialog = LoadingDialog.newInstance("请求中...");
            loadingDialog.show(getFragmentManager());
            Map<String, Object> map = new HashMap<>();
            OkHttpUtil.postJson(this, Constant.URL.save_fission, new fission(true, groupRabit), map, new OkHttpUtil.OnDataListener() {
                @Override
                public void onResponse(String url, String json) {
                    if (!TextUtils.isEmpty(json)) {
                        LogeUtil.e("save_fission", json);
                        dismissLoading();
                        fissionEntity fe = gson.fromJson(json, fissionEntity.class);
                        if (Constant.Strings.SUC.equals(fe.getCode())) {
                            if (!TextUtils.isEmpty(Percent))
                                tvPercent.setText(Percent + "%");
                        } else {
                            ToastUtil.initToast(FissionRedEnvelopeActivity.this, fe.getMsg());
                        }
                    }
                }

                @Override
                public void onFailure(String url, String error) {

                }
            });

        }
    }

    @Override
    public void cancelEnvelope() {

    }
}
